define [ 'fizz' ], (fizz) ->
  class App extends fizz.Application
    
    constructor: () ->
      super()
      @login = null
      @mediator.subscribe 'login', (login) => @login = login
      @mediator.subscribe 'controller:match:begin', @checkAuthorization, null, @
      @mediator.subscribe 'controller:match:end', @renderMenu, null, @
  
    controllerModuleNames: [
      "ioc!controller/HomeController",
      "ioc!controller/LoginController",
      "ioc!controller/WorkspaceController",
      "ioc!controller/UserController",
      "ioc!controller/RoleController"
    ]
 
    checkAuthorization: (route) ->
      # Check if the login page is show
      if route is 'login' or fizz.utils.getFragment() is 'login'
        return true
      # Check if user is logged
      if @login is null 
        res = $.get 'rest/remoteUser'
        res.done (data) =>
          if not data?.login?.length
            console.log 'no remoteUser -> go login'
            fizz.utils.reverse 'login'
          else
            console.log 'remoteUser found'
            @mediator.publish 'login', data
            fizz.utils.navigate fizz.utils.getFragment()
        res.fail (data) =>
          console.log 'fail remoteUser -> go login'
          fizz.utils.reverse 'login'
        return false

    renderMenu: (route) ->
      # Render the menus
      require [ 'ioc!topmenuView' ], (v) ->
        v.render()
      require [ 'ioc!leftmenuView' ], (v) ->
        v.render()